
package com.insigma.business.qrcode.soldier._provider.impl;


import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.poi.excel.ExcelReader;
import cn.hutool.poi.excel.ExcelUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Lists;
import com.google.common.collect.Sets;
import com.insigma.business.qrcode.common.dto.CommonRepresentationRecordBSearcher;
import com.insigma.business.qrcode.common.dto.CommonRepresentationRecordDO;
import com.insigma.business.qrcode.common.converter.CommonRepresentationRecordProviderConverter;
import com.insigma.business.qrcode.common.service.GovOrgService;

import com.insigma.business.qrcode.common.service.CommonRepresentationRecordService;
import com.insigma.business.qrcode.common.template.BasePagingResponse;
import com.insigma.business.qrcode.common.util.BizCheckUtil;
import com.insigma.business.qrcode.common.util.BizException;
import com.insigma.business.qrcode.common.util.ResponseUtils;
import com.insigma.business.qrcode.common.vo.BaseDeleteRequest;
import com.insigma.business.qrcode.common.vo.BaseResponse;
import com.insigma.business.qrcode.common.vo.ProcessStatusEnum;
import com.insigma.business.qrcode.common.vo.RepresentationTypeEnum;
import com.insigma.business.qrcode.soldier._provider.GovEmployeeProvider;
import com.insigma.business.qrcode.soldier._provider.PlacementSoldierInfoProvider;
import com.insigma.business.qrcode.soldier.dto.*;
import com.insigma.business.qrcode.common.template.area.ScenarioCodeEnum;
import com.insigma.business.qrcode.common.template.area.ServiceCallback;
import com.insigma.business.qrcode.soldier.entity.*;
import com.insigma.business.qrcode.common.dto.ErrorCodeEnum;
import com.insigma.business.qrcode.soldier.request.CommonRepresentationRecordInsertRequest;
import com.insigma.business.qrcode.soldier.request.CommonRepresentationRecordSearchRequest;
import com.insigma.business.qrcode.soldier.request.PlacementInfoSearchRequest;
import com.insigma.business.qrcode.soldier.dto.gov.BaseProviderImpl;
import com.insigma.business.qrcode.soldier.service.*;
import com.insigma.business.qrcode.common.converter.PlacementBatchProviderConverter;
import com.insigma.business.qrcode.common.converter.PlacementSoldierAspirationProviderConverter;
import com.insigma.business.qrcode.common.converter.PlacementSoldierInfoProviderConverter;
import com.insigma.business.qrcode.soldier.util.*;
import com.insigma.business.qrcode.welfare.util.PasswordUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.logging.log4j.util.Strings;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.io.InputStream;
import java.net.URL;
import java.util.*;


@Slf4j
@Service
@Component("placementSoldierInfoProvider")
public class PlacementSoldierInfoProviderImpl extends BaseProviderImpl implements PlacementSoldierInfoProvider {

    @Autowired
    private PlacementSoldierInfoService placementSoldierInfoService;

    @Autowired
    private PlacementInfoService placementInfoService;

    @Autowired
    private GovOrgService govOrgService;

    @Autowired
    private PlacementSoldierAspirationService placementSoldierAspirationService;

    @Autowired
    private PlacementSoldierAspirationResultService placementSoldierAspirationResultService;

    @Autowired
    private PlacementWordConfigService placementWordConfigService;

    @Autowired
    private CommonRepresentationRecordService commonRepresentationRecordService;

    @Autowired
    private PlacementEventRecordService placementEventRecordService;

    @Autowired
    private GovEmployeeProvider govEmployeeProvider;

    @Autowired
    private PlacementBatchService placementBatchService;

    @Autowired
    private PlacementThroughTrainApplyInfoService placementThroughTrainApplyInfoService;

    @Autowired
    private PlacementPositionInfoService placementPositionInfoService;

    @Autowired
    private MiniCacheUtils miniCacheUtils;

    @Autowired
    private CommonDataDictService commonDataDictService;

    @Autowired
    private PdfService pdfService;

    private static String proxyHost = "http://img.zhlb.tyjrswj.hangzhou.gov.cn/gongwuyuann";

    @Override
    public BasePagingResponse<List<PlacementSoldierInfoDTO>> searchPlacementSoldierInfo(final PlacementSoldierInfoSearchRequest searchRequest) {


        BizCheckUtil.checkNotNull(searchRequest, "查询分页PlacementSoldierInfo的请求参数不能为空");
        BizCheckUtil.checkNotBlank(searchRequest.getEmployeeId(), "用户id不能为空");

        String adminAreaCode = govOrgService.getAdminAreaCodeOfEmploy(searchRequest.getEmployeeId());
        searchRequest.setAdminAreaCode(adminAreaCode);

        final PlacementSoldierInfoBSearcher placementSoldierInfoBSearcher = PlacementSoldierInfoProviderConverter.convertRequestSO2Searcher(searchRequest);

        final List<PlacementSoldierInfoDO> placementSoldierInfoDOList = placementSoldierInfoService.search(placementSoldierInfoBSearcher);
        final List<PlacementSoldierInfoDTO> placementSoldierInfoDTOList = PlacementSoldierInfoProviderConverter.convertResponseDOList2DTOList(placementSoldierInfoDOList);

        if (!CollectionUtils.isEmpty(placementSoldierInfoDTOList)) {
            for (PlacementSoldierInfoDTO soldierInfoDTO : placementSoldierInfoDTOList) {
                soldierInfoDTO.setIsBaseSigned(Strings.isNotBlank(soldierInfoDTO.getBaseReviewStatus()));
                if (Strings.isNotBlank(soldierInfoDTO.getPlacementPositionId())) {
                    soldierInfoDTO.setRecruitFlag(true);
                } else {
                    soldierInfoDTO.setRecruitFlag(false);
                }
            }
        }

        return ResponseUtils.buildSuccessPagingResponse(placementSoldierInfoDTOList, placementSoldierInfoBSearcher);
    }

    @Override
    public BasePagingResponse<List<PlacementSoldierInfoDTO>> searchThoughTrain(PlacementSoldierInfoSearchRequest searchRequest) {


        BizCheckUtil.checkNotNull(searchRequest, "查询分页PlacementSoldierInfo的请求参数不能为空");
        BizCheckUtil.checkNotBlank(searchRequest.getEmployeeId(), "用户id不能为空");

        String adminAreaCode = govOrgService.getAdminAreaCodeOfEmploy(searchRequest.getEmployeeId());
        searchRequest.setAdminAreaCode(adminAreaCode);
        PlacementInfoDO alivePlacement = placementInfoService.getAlivePlacement(adminAreaCode);
        if (alivePlacement == null) {
            return ResponseUtils.buildSuccessPagingResponse(null);
        }
        PlacementBatchDO ttBatchDO = placementBatchService.getByPlacementIdAndType(alivePlacement.getId(), PlacementBatchTypeEnum.THROUGH_TRAIN.name());

        final PlacementSoldierInfoBSearcher placementSoldierInfoBSearcher = PlacementSoldierInfoProviderConverter.convertRequestSO2Searcher(searchRequest);
        placementSoldierInfoBSearcher.setType(PlacementBatchTypeEnum.THROUGH_TRAIN.name());
        placementSoldierInfoBSearcher.setSortKeyValueJoint("modifyDatetime_desc");

        final List<PlacementSoldierInfoDO> placementSoldierInfoDOList = placementSoldierInfoService.search(placementSoldierInfoBSearcher);
        final List<PlacementSoldierInfoDTO> placementSoldierInfoDTOList = PlacementSoldierInfoProviderConverter.convertResponseDOList2DTOList(placementSoldierInfoDOList);
        if (!CollectionUtils.isEmpty(placementSoldierInfoDTOList)) {
            for (PlacementSoldierInfoDTO soldierInfoDTO : placementSoldierInfoDTOList) {

                List<PlacementSoldierAspirationDO> aspirationDOS = placementSoldierAspirationService.listByIdCardNoAndBatchId(soldierInfoDTO.getIdCardNo(), ttBatchDO.getId());
                if (!CollectionUtils.isEmpty(aspirationDOS)) {
                    PlacementSoldierAspirationDO aspirationDO = aspirationDOS.get(0);
                    PlacementSoldierAspirationDTO placementSoldierAspirationDTO = PlacementSoldierAspirationProviderConverter.convertResponseDO2DTO(aspirationDO);

                    PlacementPositionInfoDO positionInfoDO = placementPositionInfoService.get(placementSoldierAspirationDTO.getPositionId());
                    if (!positionInfoDO.getType().equals(PlacementBatchTypeEnum.THROUGH_TRAIN.name())) {

                        aspirationDO = placementSoldierAspirationService.getLastDeletedThroughAsp(soldierInfoDTO.getIdCardNo());
                        placementSoldierAspirationDTO = PlacementSoldierAspirationProviderConverter.convertResponseDO2DTO(aspirationDO);
                        positionInfoDO = placementPositionInfoService.get(placementSoldierAspirationDTO.getPositionId());
                    }
                    soldierInfoDTO.setPlacementType(positionInfoDO.getThroughTrainType());
                    placementSoldierAspirationDTO.setUnitName(positionInfoDO.getUnitName());
                    placementSoldierAspirationDTO.setPositionName(positionInfoDO.getName());
                    soldierInfoDTO.setThroughTrainAspiration(placementSoldierAspirationDTO);
                }
            }
        }
        return ResponseUtils.buildSuccessPagingResponse(placementSoldierInfoDTOList, placementSoldierInfoBSearcher);
    }

    private String getCheckResult(String placementStatus, String checkType, Boolean auth) {
        if (!auth) {
            if (placementStatus.contains(checkType + "_l_" + ProcessStatusEnum.SUCCESS.name())
                    || placementStatus.contains(checkType + "_h_")) {
                return ProcessStatusEnum.SUCCESS.name();
            }
            if (placementStatus.contains(checkType + "_l_" + ProcessStatusEnum.REJECT.name())) {
                return ProcessStatusEnum.REJECT.name();
            }
        } else {
            if (placementStatus.contains(checkType + "_h_" + ProcessStatusEnum.SUCCESS.name())) {
                return ProcessStatusEnum.SUCCESS.name();
            }
            if (placementStatus.contains(checkType + "_h_" + ProcessStatusEnum.REJECT.name())) {
                return ProcessStatusEnum.REJECT.name();
            }
        }

        return ProcessStatusEnum.DEALING.name();
    }

    private List<String> buildTypeList(PlacementSoldierInfoSearchRequest searchRequest, PlacementSoldierInfoBSearcher placementSoldierInfoBSearcher, Boolean auth) {
        String checkType = searchRequest.getCheckType();

        List<String> typeList = Lists.newArrayList();
        if (Strings.isNotBlank(checkType)) {

            String status = searchRequest.getStatus();

            if (auth) {
                if (Strings.isNotBlank(status)) {
                    if (status.equals(CheckStatusEnum.DEALING.name())) {
                        typeList.add(checkType + "_l_" + ProcessStatusEnum.SUCCESS.name());
                    } else {
                        typeList.add(checkType + "_h_" + ProcessStatusEnum.SUCCESS.name());
                        typeList.add(checkType + "_h_" + ProcessStatusEnum.REJECT.name());
                    }
                } else {
                    typeList.add(checkType + "_l_" + ProcessStatusEnum.SUCCESS.name());
                    typeList.add(checkType + "_h_" + ProcessStatusEnum.SUCCESS.name());
                    typeList.add(checkType + "_h_" + ProcessStatusEnum.REJECT.name());
                }
            } else {
                if (Strings.isNotBlank(status)) {
                    if (status.equals(CheckStatusEnum.DEALING.name())) {
                        typeList.add(checkType + "_" + ProcessStatusEnum.DEALING.name());
                    } else {
                        typeList.add(checkType + "_l_" + ProcessStatusEnum.SUCCESS.name());
                        typeList.add(checkType + "_l_" + ProcessStatusEnum.REJECT.name());
                        typeList.add(checkType + "_h_" + ProcessStatusEnum.SUCCESS.name());
                        typeList.add(checkType + "_h_" + ProcessStatusEnum.REJECT.name());
                    }
                } else {
                    typeList.add(checkType + "_" + ProcessStatusEnum.DEALING.name());
                    typeList.add(checkType + "_l_" + ProcessStatusEnum.SUCCESS.name());
                    typeList.add(checkType + "_l_" + ProcessStatusEnum.REJECT.name());
                }
            }
        }
        placementSoldierInfoBSearcher.setTypeList(typeList);

        if (PlacementCheckTypeEnum.THROUGH_TRAIN.name().equals(checkType)) {
            placementSoldierInfoBSearcher.setType(PlacementCheckTypeEnum.THROUGH_TRAIN.name());
        }
        return typeList;
    }

    @Override
    public BasePagingResponse<List<PlacementSoldierInfoDTO>> searchPlacementSoldierShortInfo(PlacementSoldierInfoSearchRequest searchRequest) {

        BizCheckUtil.checkNotNull(searchRequest, "employeeId不能为空");
        BizCheckUtil.checkNotNull(searchRequest.getEmployeeId(), "employeeId不能为空");

        String adminAreaCode = govOrgService.getAdminAreaCodeOfEmploy(searchRequest.getEmployeeId());
        PlacementInfoDO alivePlacement = placementInfoService.getAlivePlacement(adminAreaCode);
        if (alivePlacement == null) {
            return ResponseUtils.buildSuccessPagingResponse(new ArrayList<>());
        }
        searchRequest.setPlacementId(alivePlacement.getId());

        final PlacementSoldierInfoBSearcher placementSoldierInfoBSearcher = PlacementSoldierInfoProviderConverter.convertRequestSO2Searcher(searchRequest);
        final List<PlacementSoldierInfoDO> placementSoldierInfoDOList = placementSoldierInfoService.search(placementSoldierInfoBSearcher);

        List<PlacementSoldierInfoDTO> result = new ArrayList<>();
        for (PlacementSoldierInfoDO soldierInfoDO : placementSoldierInfoDOList) {
            PlacementSoldierInfoDTO dto = new PlacementSoldierInfoDTO();
            dto.setRealName(soldierInfoDO.getRealName());
            dto.setIdCardNo(soldierInfoDO.getIdCardNo());
            dto.setArchiveScore(soldierInfoDO.getArchiveScore());
            dto.setExamScore(soldierInfoDO.getExamScore());
            dto.setTotalScore(soldierInfoDO.getTotalScore());
            result.add(dto);
        }
        return ResponseUtils.buildSuccessPagingResponse(result, placementSoldierInfoBSearcher);
    }

    @Override
    public BaseResponse<PlacementSoldierInfoDTO> signInByIdCardOrMobile(PlacementSoldierInfoInsertRequest request) {

        BizCheckUtil.checkNotNull(request, "请求不能为空");
        BizCheckUtil.checkNotNull(request.getSoldierId(), "id不能为空");
        BizCheckUtil.checkIsTrue(!Strings.isBlank(request.getIdCardNo()) || !Strings.isBlank(request.getMobile()), "身份校验错误");


        PlacementSoldierInfoDO soldierInfo = null;
        if (!Strings.isBlank(request.getIdCardNo())) {
            soldierInfo = placementSoldierInfoService.getByIdCardNo(request.getIdCardNo());
        }
        if (!Strings.isBlank(request.getMobile())) {
            soldierInfo = placementSoldierInfoService.getByMobile(request.getMobile());
        }
        BizCheckUtil.checkNotNull(soldierInfo, "不存在于安置名单");
        BizCheckUtil.checkIsTrue(Boolean.TRUE.equals(soldierInfo.getPublished()), "不存在于安置名单");

        soldierInfo.setSoldierId(request.getSoldierId());
        placementSoldierInfoService.update(soldierInfo);
        final PlacementSoldierInfoDTO remoteObj = PlacementSoldierInfoProviderConverter.convertResponseDO2DTO(soldierInfo);
        return ResponseUtils.buildSuccessResponse(remoteObj);
    }

    @Override
    public BaseResponse<PlacementSoldierInfoDTO> signInByPw(String idCardNo, String password, String soldierId) {


        PlacementSoldierInfoDO byIdCardNo = placementSoldierInfoService.getByIdCardNo(idCardNo);
        BizCheckUtil.checkNotNull(byIdCardNo, "登入失败");
        BizCheckUtil.checkIsTrue(Boolean.TRUE.equals(byIdCardNo.getPublished()), "不存在于安置名单");

        String encode = PasswordUtils.encode(byIdCardNo.getIdCardNo(), password);
        BizCheckUtil.checkIsTrue(byIdCardNo.getPassword().equals(encode), "密码错误");

        byIdCardNo.setSoldierId(soldierId);
        placementSoldierInfoService.update(byIdCardNo);
        final PlacementSoldierInfoDTO remoteObj = PlacementSoldierInfoProviderConverter.convertResponseDO2DTO(byIdCardNo);
        return ResponseUtils.buildSuccessResponse(remoteObj);
    }

    @Override
    public BaseResponse<PlacementSoldierInfoDTO> getPlacementSoldierInfo(String idCardNo) {

        BizCheckUtil.checkNotNull(idCardNo, "获取单条PlacementSoldierInfo的请求参数不能为空");

        final PlacementSoldierInfoDO placementSoldierInfoDO = placementSoldierInfoService.getByIdCardNo(idCardNo);
        BizCheckUtil.checkNotNull(placementSoldierInfoDO, "查无此人");
        final PlacementSoldierInfoDTO remoteObj = PlacementSoldierInfoProviderConverter.convertResponseDO2DTO(placementSoldierInfoDO);
        remoteObj.setArchiveScoreInfo(placementWordConfigService.filterByType(JSONObject.parseObject(remoteObj.getArchiveScoreDetail()),
                PlacementWordConfigAttributionEnum.PLACEMENT.name(),
                Sets.newHashSet(PlacementWordAuthEnum.FRONT.name(), PlacementWordAuthEnum.BACKEND.name())));
        remoteObj.setArchiveScoreDetail(null);

        remoteObj.setExtraInfo(placementWordConfigService.filterByType(JSONObject.parseObject(remoteObj.getExtra()),
                PlacementWordConfigAttributionEnum.PLACEMENT.name(),
                Sets.newHashSet(PlacementWordAuthEnum.FRONT.name(), PlacementWordAuthEnum.BACKEND.name())));
        remoteObj.setExtra(null);

        remoteObj.setAspiration(fillAspirations(placementSoldierInfoDO, placementSoldierInfoDO.getPlacementId(), false));
        remoteObj.setRepresentationRecords(buildScoreRepresentationRecords(idCardNo));
        return ResponseUtils.buildSuccessResponse(remoteObj);
    }

    @Override
    public BaseResponse<BinaryResultBO> getPlacementSoldierInfoOfPdf(String idCardNo) {
        PlacementSoldierInfoDTO dto = getPlacementSoldierInfo(idCardNo).getDto();
        Map<String, String> kv = new HashMap<>();
        Map<String, String> imgKv = new HashMap<>();

        buildPdfField(dto, kv, imgKv);
        try {
            byte[] bytes = pdfService.fillTemplatePdfToByte("http://img.zhlb.tyjrswj.hangzhou.gov.cn/gongwuyuann/prod/default/20220815/O2jZb9GxGAW2uXbOMs.pdf",
                    kv, imgKv);
            return ResponseUtils.buildSuccessResponse(new BinaryResultBO("xxxx.pdf", Base64.getEncoder().encodeToString(bytes)));
        } catch (Exception e) {
            log.error("{}", e);
            throw new BizException(ErrorCodeEnum.COMMON_INNER_ERROR);
        }
    }

    @Override
    public BaseResponse<BinaryResultBO> batchExportPdfByIdCardNo(PlacementSoldierInfoSearchRequest request) {

        BizCheckUtil.checkIsTrue(!CollectionUtils.isEmpty(request.getIdCardNoList()), "身份证不能为空");

        List<byte[]> result = Lists.newArrayList();
        for (String idCardNo : request.getIdCardNoList()) {
            PlacementSoldierInfoDTO dto = getPlacementSoldierInfo(idCardNo).getDto();
            Map<String, String> kv = new HashMap<>();
            Map<String, String> imgKv = new HashMap<>();
            buildPdfField(dto, kv, imgKv);
            try {
                byte[] bytes = pdfService.fillTemplatePdfToByte("http://img.zhlb.tyjrswj.hangzhou.gov.cn/gongwuyuann/prod/default/20220815/O2jZb9GxGAW2uXbOMs.pdf",
                        kv, imgKv);
                result.add(bytes);
            } catch (Exception e) {
                log.error("{}", e);
                throw new BizException(ErrorCodeEnum.COMMON_INNER_ERROR);
            }
        }
        byte[] mergepdf = pdfService.mergepdf(result);
        return ResponseUtils.buildSuccessResponse(new BinaryResultBO("xxxx.pdf", Base64.getEncoder().encodeToString(mergepdf)));
    }

    private void buildPdfField(PlacementSoldierInfoDTO dto, Map<String, String> kv, Map<String, String> imgKv) {
        kv.put("realName", dto.getRealName());
        kv.put("idCardNo", dto.getIdCardNo());
        kv.put("gender", dto.getGender().equals("MALE") ? "男" : "女");
        kv.put("mobile", dto.getMobile());
        kv.put("birthday", DateUtil.format(dto.getBirthday(), "yyyy-MM-dd"));
        kv.put("college", dto.getCollege());
        kv.put("emergencyName", dto.getEmergencyName());
        kv.put("emergencyRelationship", dto.getEmergencyRelationship());
        kv.put("emergencyMobile", dto.getEmergencyMobile());

        kv.put("archiveScore", FieldUtils.toString(dto.getArchiveScore()));
        kv.put("totalScore", FieldUtils.toString(dto.getTotalScore()));
        LinkedHashMap archiveScoreInfo = dto.getArchiveScoreInfo();
        if (archiveScoreInfo != null) {
            kv.put("ageScore", FieldUtils.toString(archiveScoreInfo.get("ageScore")));
            kv.put("rankScore", FieldUtils.toString(archiveScoreInfo.get("rankScore")));
            kv.put("preferentialTreatmentScore", FieldUtils.toString(archiveScoreInfo.get("preferentialTreatmentScore")));
            kv.put("rewardScore", FieldUtils.toString(archiveScoreInfo.get("rewardScore")));
            kv.put("eduScore", FieldUtils.toString(archiveScoreInfo.get("eduScore")));
            kv.put("jobScore", FieldUtils.toString(archiveScoreInfo.get("jobScore")));
            kv.put("disciplineScore", FieldUtils.toString(archiveScoreInfo.get("disciplineScore")));
        }

        kv.put("examScore", FieldUtils.toString(dto.getExamScore()));

        if (dto.getAspiration() != null) {
            int loop = 0;
            for (PlacementSoldierAspirationDTO placementSoldierAspirationDTO : dto.getAspiration()) {
                kv.put("xh" + loop, String.valueOf(loop));
                kv.put("gwxz" + loop, placementSoldierAspirationDTO.getPositionName());
                kv.put("dwmc" + loop, placementSoldierAspirationDTO.getUnitName());
                kv.put("jg" + loop, "SUCCESS".equals(placementSoldierAspirationDTO.getStatus()) ? "成功" : "");
                String sign = placementSoldierAspirationDTO.getSign();
                if (Strings.isNotBlank(sign)) {
                    imgKv.put("qm" + loop, proxyHost + "/" + sign);
                }
                loop++;
            }
        }

        String baseSign = dto.getBaseSign();
        if (Strings.isNotBlank(baseSign)) {
            imgKv.put("baseSign", proxyHost + "/" + baseSign);
        }

        String scoreSign = dto.getScoreSign();
        if (Strings.isNotBlank(scoreSign)) {
            imgKv.put("scoreSign", proxyHost + "/" + scoreSign);
        }

        List<PlacementSoldierAspirationDTO> aspiration = dto.getAspiration();
        if (aspiration != null) {
            for (PlacementSoldierAspirationDTO placementSoldierAspirationDTO : aspiration) {
                int loop = 0;
            }
        }
    }

    private List<CommonRepresentationRecordDTO> buildScoreRepresentationRecords(String idCardNo) {
        List<CommonRepresentationRecordDO> commonRepresentationRecordDOS = commonRepresentationRecordService.listByIdCardNoAndType(idCardNo,
                RepresentationTypeEnum.PLACEMENT.name());
        final List<CommonRepresentationRecordDTO> commonRepresentationRecordDTOList = CommonRepresentationRecordProviderConverter.convertResponseDOList2DTOList(commonRepresentationRecordDOS);

        return commonRepresentationRecordDTOList;
    }

    private List<PlacementSoldierAspirationDTO> fillAspirations(PlacementSoldierInfoDO soldierInfo, String placementId, Boolean isSoldier) {
        String idCardNo = soldierInfo.getIdCardNo();
        List<PlacementSoldierAspirationDO> aspirationDOS = placementSoldierAspirationService.listByIdCardNo(idCardNo);
        final List<PlacementSoldierAspirationDTO> aspirationDTOS = PlacementSoldierAspirationProviderConverter.convertResponseDOList2DTOList(aspirationDOS);
        Collections.sort(aspirationDTOS, new Comparator<PlacementSoldierAspirationDTO>() {
            @Override
            public int compare(PlacementSoldierAspirationDTO o1, PlacementSoldierAspirationDTO o2) {
                return o1.getSeqNo().compareTo(o2.getSeqNo());
            }
        });

        if (CollectionUtils.isEmpty(aspirationDTOS)) {
            return new ArrayList<>();
        }
        String batchId = aspirationDTOS.get(0).getBatchId();
        PlacementBatchDO placementBatchDO = placementBatchService.get(batchId);

        Boolean viewFlag = checkUniCanView(placementBatchDO.getPlacementId());
        if (!isSoldier && !viewFlag && placementBatchDO.getType().equals(PlacementBatchTypeEnum.UNIFIED.name())) {
            return null;
        }

        PlacementSoldierAspirationResultDO aspirationResultDO = placementSoldierAspirationResultService.getByIdCardNo(idCardNo);
        if (!CollectionUtils.isEmpty(aspirationDTOS)) {
            for (PlacementSoldierAspirationDTO aspirationDTO : aspirationDTOS) {
                String positionId = aspirationDTO.getPositionId();
                PlacementPositionInfoDO cachedPlacementPosition = miniCacheUtils.getCachedPlacementPosition(positionId);
                aspirationDTO.setPositionName(cachedPlacementPosition.getName());
                aspirationDTO.setUnitName(cachedPlacementPosition.getUnitName());
                aspirationDTO.setQuota(cachedPlacementPosition.getQuota());
                aspirationDTO.setCode(cachedPlacementPosition.getCode());
                if (!isSoldier) {
                    aspirationDTO.setRank(getRank(soldierInfo, positionId));
                }
            }

            if (placementBatchDO.getStatus().equals(ProcessStatusEnum.SUCCESS.name())) {
                if (aspirationResultDO != null) {
                    for (PlacementSoldierAspirationDTO aspirationDTO : aspirationDTOS) {
                        if (aspirationDTO.getPositionId().equals(aspirationResultDO.getPositionId())) {
                            aspirationDTO.setAdmitted(PlacementAspirationResultStatusEnum.SUCCESS.name());
                            break;
                        } else {
                            aspirationDTO.setAdmitted(PlacementAspirationResultStatusEnum.FAILED.name());
                        }
                    }
                } else {
                    for (PlacementSoldierAspirationDTO aspirationDTO : aspirationDTOS) {
                        aspirationDTO.setAdmitted(PlacementAspirationResultStatusEnum.FAILED.name());
                    }
                }
            }


            if (PlacementBatchTypeEnum.THROUGH_TRAIN.name().equals(placementBatchDO.getType()) && aspirationResultDO != null) {
                for (PlacementSoldierAspirationDTO aspirationDTO : aspirationDTOS) {
                    String positionId = aspirationDTO.getPositionId();
                    PlacementPositionInfoDO positionInfoDO = placementPositionInfoService.get(positionId);
                    if ("3_SUCCESS".equals(positionInfoDO.getAuditStatus()) && positionId.equals(aspirationResultDO.getPositionId())) {
                        aspirationDTO.setAdmitted(PlacementAspirationResultStatusEnum.SUCCESS.name());
                    }
                }
            }
        }

        return aspirationDTOS;
    }


    private Integer getRank(PlacementSoldierInfoDO soldierInfo, String positionId) {
        Double totalScore = soldierInfo.getTotalScore();
        if (totalScore == null) {
            return null;
        }

        List<PlacementSoldierInfoDO> placementSoldierInfoDOS = placementSoldierInfoService.listByPositionId(positionId);
        int rank = 1;
        for (PlacementSoldierInfoDO placementSoldierInfoDO : placementSoldierInfoDOS) {
            if (placementSoldierInfoDO.getTotalScore() != null) {
                if (totalScore < placementSoldierInfoDO.getTotalScore()) {
                    rank++;
                }
            }
        }
        return rank;
    }

    @Override
    public BaseResponse<PlacementSoldierInfoDTO> getFilteredSoldierDetail(String soldierId) {

        BizCheckUtil.checkNotNull(soldierId, "请求不能为空");
        PlacementSoldierInfoDO soldierInfoDO = placementSoldierInfoService.getBySoldierId(soldierId);
        BizCheckUtil.checkNotNull(soldierInfoDO, "查无此人");

        final PlacementSoldierInfoDTO remoteObj = PlacementSoldierInfoProviderConverter.convertResponseDO2DTO(soldierInfoDO);
        remoteObj.setArchiveScoreInfo(placementWordConfigService.filterByType(JSONObject.parseObject(remoteObj.getArchiveScoreDetail()),
                PlacementWordConfigAttributionEnum.PLACEMENT.name(),
                Sets.newHashSet(PlacementWordAuthEnum.FRONT.name())));
        remoteObj.setArchiveScoreDetail(null);

        remoteObj.setExtraInfo(placementWordConfigService.filterByType(JSONObject.parseObject(remoteObj.getExtra()),
                PlacementWordConfigAttributionEnum.PLACEMENT.name(),
                Sets.newHashSet(PlacementWordAuthEnum.FRONT.name())));
        remoteObj.setExtra(null);
        if (remoteObj.getArchiveScore() != null) {
            remoteObj.setIsArchiveInit(true);
        } else {
            remoteObj.setIsArchiveInit(false);
        }
        return ResponseUtils.buildSuccessResponse(remoteObj);
    }

    @Override
    public BaseResponse<PlacementAspirationResultDetailDTO> getPlacementSoldierAspirationResult(String soldierId) {

        BizCheckUtil.checkNotNull(soldierId, "请求不能为空");
        PlacementSoldierInfoDO soldierInfoDO = placementSoldierInfoService.getBySoldierId(soldierId);
        log.info("查询 soldierInfoDO 结果:{}", soldierInfoDO);
        BizCheckUtil.checkNotNull(soldierInfoDO, "查无此人");

        int archiveScoreRankNum = 1;
        int archiveScoreTiedNum = -1;
        Integer examScoreRankNum = 1;
        Integer examScoreTiedNum = -1;
        Integer totalScoreRankNum = 1;
        Integer totalScoreTiedNum = -1;

        final PlacementAspirationResultDetailDTO remoteObj = new PlacementAspirationResultDetailDTO();
        remoteObj.setAspiration(fillAspirations(soldierInfoDO, soldierInfoDO.getPlacementId(), true));
        remoteObj.setArchiveScore(String.format("%.2f", soldierInfoDO.getArchiveScore()));
        remoteObj.setArchiveScoreRankNum(archiveScoreRankNum);


        if (examScoreRankNum != null) {


            if (soldierInfoDO.getTotalScore() != null) {
                remoteObj.setTotalScore(String.format("%.2f", soldierInfoDO.getTotalScore()));
            }
            remoteObj.setTotalScoreRankNum(totalScoreRankNum);
            remoteObj.setTotalScoreTiedNum(totalScoreTiedNum);
        }


        PlacementBatchDO placementBatchDO = placementBatchService.get(soldierInfoDO.getBatchId());
        log.info("查询placementBatchDO 结果:{}", placementBatchDO);
        remoteObj.setBatchType(placementBatchDO.getType());
        PlacementBatchDO currentBatch = placementBatchService.getCurrentBatch(soldierInfoDO.getPlacementId());
        log.info("查询currentBatch 结果:{}", currentBatch);
        if (currentBatch != null) {
            remoteObj.setCurrentBatchType(currentBatch.getType());
        }
        if (PlacementBatchTypeEnum.THROUGH_TRAIN.name().equals(placementBatchDO.getType())) {
            List<PlacementPositionInfoDO> placementPositionInfoDOS = placementPositionInfoService.listByIdCardNoAndBatchType(PrivacyEncUtils.encodeIdCardNo(soldierInfoDO.getIdCardNo()), PlacementBatchTypeEnum.THROUGH_TRAIN.name());
            log.info("查询placementPositionInfoDOS 结果:{}", placementPositionInfoDOS);
            log.info("分支1-1");
            if (!CollectionUtils.isEmpty(placementPositionInfoDOS)) {
                PlacementPositionInfoDO lastOne = placementPositionInfoDOS.get(placementPositionInfoDOS.size() - 1);
                if ("3_SUCCESS".equals(lastOne.getAuditStatus())) {
                    log.info("分支1-1-1");
                    remoteObj.setResultPublished(true);
                } else {
                    log.info("分支1-1-2");
                    remoteObj.setResultPublished(false);
                }
            } else {
                log.info("分支1-2");
                remoteObj.setResultPublished(false);
            }

        } else {
            Boolean resultPublished = placementBatchService.isResultPublished(soldierInfoDO.getBatchId());
            log.info("查询resultPublished 结果:{}", resultPublished);

            List<PlacementPositionInfoDO> uo = new ArrayList<>();
            List<PlacementPositionInfoDO> u1 = placementPositionInfoService.listByIdCardNoAndBatchType(soldierInfoDO.getIdCardNo(), PlacementBatchTypeEnum.UNIFIED.name());
            List<PlacementPositionInfoDO> u2 = placementPositionInfoService.listByIdCardNoAndBatchType(soldierInfoDO.getIdCardNo(), PlacementBatchTypeEnum.OFFLINE.name());
            uo.addAll(u1);
            uo.addAll(u2);

            if (!CollectionUtils.isEmpty(uo)) {
                PlacementPositionInfoDO lastOne = uo.get(uo.size() - 1);
                log.info("lastOne:{}", lastOne);
                log.info("分支2-1");
                if ("3_SUCCESS".equals(lastOne.getAuditStatus())) {
                    log.info("分支2-1-1");
                    remoteObj.setResultPublished(resultPublished);
                } else {
                    log.info("分支2-1-2");
                    remoteObj.setResultPublished(false);
                }
            } else {
                log.info("分支2-2");
                remoteObj.setResultPublished(false);
            }

            if (currentBatch == null) {
                remoteObj.setResultPublished(resultPublished);
            }

        }
        if (remoteObj.getResultPublished() && soldierInfoDO.getExamScore() != null) {
            remoteObj.setExamScore(String.format("%.2f", soldierInfoDO.getExamScore()));
            remoteObj.setTotalScore(String.format("%.2f", soldierInfoDO.getTotalScore()));
        } else {
            remoteObj.setTotalScore(null);
        }

        remoteObj.setPublishDatetime(placementBatchDO.getPublishDatetime());
        remoteObj.setStatus(buildMatchResult(remoteObj));
        remoteObj.setAspirationEdited(buildIfAspirationCanEdit(soldierInfoDO, remoteObj));
        return ResponseUtils.buildSuccessResponse(remoteObj);
    }

    private Boolean buildIfAspirationCanEdit(PlacementSoldierInfoDO soldierInfoDO, PlacementAspirationResultDetailDTO remoteObj) {
        if (remoteObj.getStatus().equals(ProcessStatusEnum.SUCCESS.name())) {
            return false;
        }

        if (remoteObj.getStatus().equals(ProcessStatusEnum.DEALING.name())) {
            Boolean applyEnd = placementBatchService.isApplyEnd(soldierInfoDO.getBatchId());
            return applyEnd;
        }

        if (!remoteObj.getStatus().equals(ProcessStatusEnum.DEALING.name())) {

            String placementId = soldierInfoDO.getPlacementId();
            PlacementBatchDO currentBatch = placementBatchService.getCurrentBatch(placementId);
            if (currentBatch != null && currentBatch.getStatus().equals(ProcessStatusEnum.DEALING.name())) {
                return true;
            }
        }
        return false;
    }

    private String buildMatchResult(PlacementAspirationResultDetailDTO remoteObj) {
        if (remoteObj.getResultPublished()) {
            boolean matched = false;
            for (PlacementSoldierAspirationDTO placementSoldierAspirationDTO : remoteObj.getAspiration()) {
                if (ProcessStatusEnum.SUCCESS.name().equals(placementSoldierAspirationDTO.getAdmitted())) {
                    matched = true;
                    break;
                }
            }
            return matched ? ProcessStatusEnum.SUCCESS.name() : ProcessStatusEnum.REJECT.name();
        }

        return ProcessStatusEnum.DEALING.name();
    }


    @Override
    public BaseResponse<PlacementSoldierInfoDTO> getPlacementProcess(String soldierId) {

        BizCheckUtil.checkNotNull(soldierId, "请求不能为空");

        PlacementSoldierInfoDO soldierInfo = placementSoldierInfoService.getBySoldierId(soldierId);
        if (soldierInfo == null) {
            return ResponseUtils.buildSuccessResponse(new PlacementSoldierInfoDTO(PlacementProcessStatusEnum.NULL.name()));
        }
        PlacementInfoDO placementInfoDO = placementInfoService.get(soldierInfo.getPlacementId());
        if (placementInfoDO == null) {
            return ResponseUtils.buildSuccessResponse(new PlacementSoldierInfoDTO(PlacementProcessStatusEnum.NULL.name()));
        }

        PlacementSoldierInfoDTO remoteObj = PlacementSoldierInfoProviderConverter.convertResponseDO2DTO(soldierInfo);
        if (remoteObj.getArchiveScore() != null) {
            remoteObj.setIsArchiveInit(true);
        } else {
            remoteObj.setIsArchiveInit(false);
        }
        remoteObj.setExtra(null);
        PlacementBatchDO currentBatch = placementBatchService.getCurrentBatch(soldierInfo.getPlacementId());
        if (currentBatch != null) {
            remoteObj.setCanApply(currentBatch.getApplyEndDatetime().compareTo(new Date()) > 0 && currentBatch.getCanApply());
        }

        remoteObj.setProcess(currentBatch != null ? currentBatch.getType() : "");
        remoteObj.setStatus(buildProcessStatus(soldierInfo));

        remoteObj.setFlow(buildFlow(soldierInfo));
        remoteObj.setCurrentTask(buildCurrentTask(soldierInfo));
        remoteObj.setCanFillIn(true);

        List<PlacementSoldierAspirationDO> aspirationDOS = placementSoldierAspirationService.listByIdCardNo(soldierInfo.getIdCardNo());
        remoteObj.setIsThroughTrainApply(false);
        if (!CollectionUtils.isEmpty(aspirationDOS)) {
            PlacementSoldierAspirationDO aspirationDO = aspirationDOS.get(0);
            PlacementPositionInfoDO positionInfoDO = placementPositionInfoService.get(aspirationDO.getPositionId());
            if (PlacementBatchTypeEnum.THROUGH_TRAIN.name().equals(positionInfoDO.getType())) {
                remoteObj.setThroughTrainApplyStatus(aspirationDO.getStatus());
                remoteObj.setIsThroughTrainApply(true);
                if (aspirationDO.getStatus().equals(ThroughTrainProcessEnum.REJECT.name()) || aspirationDO.getStatus().equals(ThroughTrainProcessEnum.SUCCESS.name())) {
                    remoteObj.setCanFillIn(false);
                }
            }
        }

        remoteObj.setHasRepresentation(isHasRepresentation(soldierInfo));
        return ResponseUtils.buildSuccessResponse(remoteObj);
    }

    private Boolean isHasRepresentation(PlacementSoldierInfoDO soldierInfo) {
        List<CommonRepresentationRecordDO> commonRepresentationRecordDOS = commonRepresentationRecordService.listByIdCardNoAndType(soldierInfo.getIdCardNo(),
                RepresentationTypeEnum.PLACEMENT.name());
        if (CollectionUtils.isEmpty(commonRepresentationRecordDOS)) {
            return false;
        }
        return true;
    }

    private String buildProcessStatus(PlacementSoldierInfoDO infoDO) {
        if (PlacementScoreReviewEnum.PASS.name().equals(infoDO.getScoreReviewStatus())) {
            List<PlacementSoldierAspirationDO> aspirationDOS = placementSoldierAspirationService.listByIdCardNo(infoDO.getIdCardNo());
            if (!CollectionUtils.isEmpty(aspirationDOS)) {

                PlacementBatchDO placementBatchDO = placementBatchService.get(infoDO.getBatchId());
                if (PlacementBatchTypeEnum.THROUGH_TRAIN.name().equals(placementBatchDO.getType())) {
                    List<PlacementPositionInfoDO> placementPositionInfoDOS = placementPositionInfoService.listByIdCardNoAndBatchType(infoDO.getIdCardNo(), PlacementBatchTypeEnum.THROUGH_TRAIN.name());
                    if (!CollectionUtils.isEmpty(placementPositionInfoDOS)) {
                        PlacementPositionInfoDO lastOne = placementPositionInfoDOS.get(placementPositionInfoDOS.size() - 1);
                        if ("3_SUCCESS".equals(lastOne.getAuditStatus())) {
                            return PlacementProcessStatusEnum.ASPIRATION_RESULT.name();
                        }
                    }
                }

                return PlacementProcessStatusEnum.ASPIRATION_SUBMIT.name();
            }

            return PlacementProcessStatusEnum.SCORE_REVIEW.name();
        }

        if (PlacementScoreReviewEnum.PASS.name().equals(infoDO.getBaseReviewStatus())) {
            return PlacementProcessStatusEnum.BASE_REVIEW.name();
        }

        return PlacementProcessStatusEnum.REGISTERED.name();
    }

    private String buildCurrentTask(PlacementSoldierInfoDO soldierInfo) {
        if (Strings.isBlank(soldierInfo.getBaseReviewStatus())) {
            return "请对个人信息进行审核！";
        }

        if (Strings.isBlank(soldierInfo.getScoreReviewStatus())) {
            return PlacementScoreReviewEnum.UNDO.getTask();
        }

        if (soldierInfo.getScoreReviewStatus().equals(PlacementScoreReviewEnum.PASS.name())) {

            int i = placementSoldierAspirationService.countBySoldier(soldierInfo.getSoldierId());
            if (i > 0) {
                PlacementBatchDO placementBatchDO = placementBatchService.get(soldierInfo.getBatchId());
                if (ProcessStatusEnum.SUCCESS.name().equals(placementBatchDO.getStatus())) {
                    return "请查看志愿结果";
                } else {
                    return "请等待结果";
                }
            } else {
                return PlacementScoreReviewEnum.PASS.getTask();
            }
        }

        if (soldierInfo.getScoreReviewStatus().equals(PlacementScoreReviewEnum.FAIL.name())) {
            return PlacementScoreReviewEnum.FAIL.getTask();
        }

        return null;
    }

    private List<FlowDetailDTO> buildFlow(PlacementSoldierInfoDO soldierInfo) {
        List<FlowDetailDTO> list = new ArrayList<>();
        List<PlacementEventRecordDO> placementEventRecordDOS = placementEventRecordService.listBySoldierId(soldierInfo.getSoldierId());
        if (!CollectionUtils.isEmpty(placementEventRecordDOS)) {
            for (PlacementEventRecordDO placementEventRecordDO : placementEventRecordDOS) {
                FlowDetailDTO flowDetailDTO = new FlowDetailDTO();
                flowDetailDTO.setOperateTime(placementEventRecordDO.getCreateDatetime());
                flowDetailDTO.setMessage(placementEventRecordDO.getDetail());
                list.add(flowDetailDTO);
            }
        }
        return list;
    }


    @Override
    public BaseResponse<String> insertPlacementSoldierInfo(final PlacementSoldierInfoInsertRequest insertRequest) {

        final BaseResponse<String> baseResponse = new BaseResponse<>();
        serviceTemplate.execute(transactionTemplate, baseResponse, new ServiceCallback() {
            @Override
            public void check() {
                BizCheckUtil.checkNotNull(insertRequest, "新增PlacementSoldierInfo的请求参数不能为空");
            }

            @Override
            public void executeService() {
                final PlacementSoldierInfoDO placementSoldierInfoDO = PlacementSoldierInfoProviderConverter.convertRequestIO2DO(insertRequest);
                placementSoldierInfoService.insert(placementSoldierInfoDO);
                ResponseUtils.setupSuccessResponse(baseResponse, placementSoldierInfoDO.getId());
            }

            @Override
            public ScenarioCodeEnum getScenarioEnum() {
                return ScenarioCodeEnum.PLACEMENT_SOLDIER_INFO_INSERT;
            }
        });
        return baseResponse;
    }

    @Transactional()
    @Override
    public BaseResponse<String> importPlacementSoldiers(SimpleApiRequest request) {

        BizCheckUtil.checkNotNull(request, "请求不能为空");
        BizCheckUtil.checkNotNull(request.getUrl(), "url不能为空");
        BizCheckUtil.checkNotNull(request.getEmployeeId(), "employeeId不能为空");

        String adminAreaCode = govOrgService.getAdminAreaCodeOfEmploy(request.getEmployeeId());
        String url = request.getUrl();
        url = url.replace("115.227.32.11", "172.18.102.62");
        try {
            URL source = new URL(url);
            InputStream inputStream = source.openStream();
            ExcelReader reader = ExcelUtil.getReader(inputStream);

            final List<List<Object>> read = reader.read();

            PlacementInfoDO alivePlacement = placementInfoService.getAlivePlacement(adminAreaCode);
            BizCheckUtil.checkNotNull(alivePlacement, "暂无安置");

            PlacementBatchDO batchDO = placementBatchService.getByPlacementIdAndType(alivePlacement.getId(), PlacementBatchTypeEnum.UNIFIED.name());

            List<Object> objects = read.get(0);
            String[] strings = {"序号", "姓名", "身份证号", "性别", "民族", "联系电话",
                    "全日制学历学位", "全日制毕业院校及专业", "紧急联系人姓名", "紧急联系人关系", "紧急联系人手机号码"};
            checkSoldierImportTemplate(objects, strings);

            for (List<Object> item : read) {
                for (int i = item.size(); i < strings.length; i++) {
                    item.add(null);
                }
            }
            for (int i = 1; i < read.size(); i++) {
                List<Object> item = read.get(i);
                String realName = (String) item.get(1);
                String idCardNo = (String) item.get(2);
                String genderCN = (String) item.get(3);
                String nation = (String) item.get(4);
                String mobile = (String) item.get(5);
                String education = (String) item.get(6);
                String college = (String) item.get(7);
                String emergencyName = (String) item.get(8);
                String emergencyRelationship = (String) item.get(9);
                String emergencyMobile = (String) item.get(10);

                PlacementSoldierInfoDO byIdCardNo = placementSoldierInfoService.getByIdCardNo(idCardNo);
                PlacementSoldierInfoDO soldierInfoDO = null;
                if (byIdCardNo != null) {
                    soldierInfoDO = byIdCardNo;
                } else {
                    soldierInfoDO = new PlacementSoldierInfoDO();
                }

                soldierInfoDO.setPlacementId(alivePlacement.getId());
                soldierInfoDO.setBatchId(batchDO.getId());
                soldierInfoDO.setType(batchDO.getType());
                soldierInfoDO.setIdCardNo(idCardNo);
                soldierInfoDO.setPassword(PasswordUtils.encode(idCardNo, idCardNo.substring(idCardNo.length() - 6)));

                String s = DateUtils.idCardNoToBirthday(idCardNo);
                soldierInfoDO.setBirthday(DateUtil.parse(s, "yyyy-MM-dd"));

                soldierInfoDO.setRealName(realName);
                soldierInfoDO.setGender(genderCN.equals("女") ? "FEMALE" : "MALE");
                soldierInfoDO.setMobile(mobile);
                soldierInfoDO.setEducationLevel(education);
                soldierInfoDO.setAdminAreaCode(adminAreaCode);
                soldierInfoDO.setPlacementStatus(ProcessStatusEnum.DEALING.name());

                soldierInfoDO.setNation(nation);
                soldierInfoDO.setCollege(college);
                soldierInfoDO.setEmergencyName(emergencyName);
                soldierInfoDO.setEmergencyMobile(emergencyMobile);
                soldierInfoDO.setEmergencyRelationship(emergencyRelationship);

                if (byIdCardNo != null) {
                    placementSoldierInfoService.update(soldierInfoDO);
                } else {
                    placementSoldierInfoService.insert(soldierInfoDO);
                }
            }

        } catch (BizException e) {
            log.error("导出出错：{}", e);
            throw e;
        } catch (Exception e) {
            log.error("导出出错：{}", e);
            throw new BizException(ErrorCodeEnum.ILLEGAL_PARAM);
        }

        return ResponseUtils.buildSuccessResponse("处理成功");
    }

    @Override
    public BaseResponse<String> importPlacementArchiveScore(SimpleApiRequest request) {

        BizCheckUtil.checkNotNull(request, "请求不能为空");
        BizCheckUtil.checkNotNull(request.getUrl(), "url不能为空");
        BizCheckUtil.checkNotNull(request.getEmployeeId(), "employeeId不能为空");

        String adminAreaCode = govOrgService.getAdminAreaCodeOfEmploy(request.getEmployeeId());
        String url = request.getUrl();
        url = url.replace("115.227.32.11", "172.18.102.62");
        try {
            URL source = new URL(url);
            InputStream inputStream = source.openStream();
            ExcelReader reader = ExcelUtil.getReader(inputStream);

            final List<List<Object>> read = reader.read();

            PlacementInfoDO alivePlacement = placementInfoService.getAlivePlacement(adminAreaCode);
            BizCheckUtil.checkNotNull(alivePlacement, "暂无安置");


            List<Object> objects = read.get(0);
            checkSoldierImportTemplate(objects, "序号", "姓名", "身份证号码", "军龄分", "职级分", "职务分", "奖励分", "优待分", "学历分", "惩戒分", "合计");
            for (int i = 1; i < read.size(); i++) {
                List<Object> item = read.get(i);
                String realName = (String) item.get(1);
                String idCardNo = (String) item.get(2);
                Object archiveScore = item.get(10);

                PlacementSoldierInfoDO soldierInfoDO = placementSoldierInfoService.getByIdCardNo(idCardNo);
                if (soldierInfoDO == null) {


                    continue;
                }
                soldierInfoDO.setArchiveScore(FieldUtils.objectToDouble(archiveScore));
                soldierInfoDO.setArchiveScoreDetail(buildArchiveScoreDetailOfShort(item));
                soldierInfoDO.setAdminAreaCode(adminAreaCode);
                soldierInfoDO.setPlacementStatus(ProcessStatusEnum.DEALING.name());
                placementSoldierInfoService.update(soldierInfoDO);
            }

        } catch (BizException e) {
            log.error("导出出错：{}", e);
            throw e;
        } catch (Exception e) {
            log.error("导出出错：{}", e);
            throw new BizException(ErrorCodeEnum.ILLEGAL_PARAM);
        }

        return ResponseUtils.buildSuccessResponse("处理成功");
    }

    private String buildInitStatus() {
        List<String> list = Lists.newArrayList();
        for (PlacementCheckTypeEnum value : PlacementCheckTypeEnum.values()) {
            list.add(value.name() + "_" + ProcessStatusEnum.DEALING.name());
        }
        return String.join(",", list);
    }


    private String buildArchiveScoreDetailOfShort(List<Object> item) {
        Object ageScore = item.get(3);
        Object rankScore = item.get(4);
        Object jobScore = item.get(5);
        Object rewardScore = item.get(6);
        Object preferentialTreatmentScore = item.get(7);
        Object eduScore = item.get(8);
        Object disciplineScore = item.get(9);
        Object total = item.get(10);

        JSONObject o = new JSONObject();
        o.put("ageScore", nullToZero(ageScore));
        o.put("rankScore", nullToZero(rankScore));
        o.put("preferentialTreatmentScore", nullToZero(preferentialTreatmentScore));
        o.put("rewardScore", nullToZero(rewardScore));
        o.put("eduScore", nullToZero(eduScore));
        o.put("jobScore", nullToZero(jobScore));
        o.put("disciplineScore", nullToZero(disciplineScore));
        o.put("total", nullToZero(total));
        return o.toJSONString();
    }

    private Long nullToZero(Object o) {
        if (o == null) {
            return 0L;
        }
        if (o instanceof String) {
            if (Strings.isBlank((String) o)) {
                return 0L;
            }
        }

        return Long.valueOf(o.toString());
    }


    private String buildArchiveScoreDetail(List<Object> item) {
        String ageScore = (String) item.get(12);
        String rankScore = (String) item.get(13);
        String preferentialTreatmentScore = (String) item.get(14);
        String rewardScore = (String) item.get(15);
        String eduScore = (String) item.get(16);
        String administrativeSanctionScore = (String) item.get(17);
        String partySanctionScore = (String) item.get(18);
        String addSubtotal = (String) item.get(19);
        String deductionSubtotal = (String) item.get(20);
        String total = (String) item.get(11);

        JSONObject o = new JSONObject();
        o.put("ageScore", ageScore);
        o.put("rankScore", rankScore);
        o.put("preferentialTreatmentScore", preferentialTreatmentScore);
        o.put("rewardScore", rewardScore);
        o.put("eduScore", eduScore);
        o.put("administrativeSanctionScore", administrativeSanctionScore);
        o.put("partySanctionScore", partySanctionScore);
        o.put("addSubtotal", addSubtotal);
        o.put("deductionSubtotal", deductionSubtotal);
        o.put("total", total);
        return o.toJSONString();
    }

    @Override
    public BaseResponse<String> importExamScore(SimpleApiRequest request) {

        BizCheckUtil.checkNotNull(request, "请求不能为空");
        BizCheckUtil.checkNotNull(request.getUrl(), "url不能为空");
        BizCheckUtil.checkNotNull(request.getEmployeeId(), "employeeId不能为空");

        String adminAreaCode = govOrgService.getAdminAreaCodeOfEmploy(request.getEmployeeId());
        String url = request.getUrl();
        url = url.replace("115.227.32.11", "172.18.102.62");
        try {
            URL source = new URL(url);
            InputStream inputStream = source.openStream();
            ExcelReader reader = ExcelUtil.getReader(inputStream);

            final List<List<Object>> read = reader.read();

            PlacementInfoDO alivePlacement = placementInfoService.getAlivePlacement(adminAreaCode);
            BizCheckUtil.checkNotNull(alivePlacement, "暂无安置");


            List<Object> objects = read.get(0);
            checkSoldierImportTemplate(objects, "姓名", "身份证", "准考证号", "考试分");
            for (int i = 1; i < read.size(); i++) {
                List<Object> item = read.get(i);
                String realName = (String) item.get(0);
                String idCardNo = (String) item.get(1);
                Object score = item.get(3);

                PlacementSoldierInfoDO byIdCardNo = placementSoldierInfoService.getByIdCardNo(idCardNo);
                if (byIdCardNo == null) {
                    byIdCardNo = placementSoldierInfoService.getByName(realName.trim(), alivePlacement.getId());
                    if (byIdCardNo == null) {
                        continue;
                    }
                }
                byIdCardNo.setExamScore(Double.valueOf(score.toString()));
                byIdCardNo.setTotalScore(byIdCardNo.getArchiveScore() + byIdCardNo.getExamScore());
                placementSoldierInfoService.update(byIdCardNo);
            }

        } catch (BizException e) {
            log.error("导入考试分错误：{}", e);
            throw e;
        } catch (Exception e) {
            log.error("导入考试分错误：{}", e);
            throw new BizException(ErrorCodeEnum.ILLEGAL_PARAM);
        }

        return ResponseUtils.buildSuccessResponse("处理成功");
    }

    @Override
    public BaseResponse<ExcelResultBO> exportSoliderInfo(PlacementSoldierInfoSearchRequest searchRequest) {


        BizCheckUtil.checkNotBlank(searchRequest.getEmployeeId(), "用户id不能为空");

        String adminAreaCode = govOrgService.getAdminAreaCodeOfEmploy(searchRequest.getEmployeeId());
        searchRequest.setAdminAreaCode(adminAreaCode);

        final PlacementSoldierInfoBSearcher placementSoldierInfoBSearcher = PlacementSoldierInfoProviderConverter.convertRequestSO2Searcher(searchRequest);

        final List<PlacementSoldierInfoDO> placementSoldierInfoDOList = placementSoldierInfoService.search(placementSoldierInfoBSearcher);

        List<String> headers = Lists.newArrayList("姓名", "身份证", "性别", "出生日期", "手机号", "学历", "专业", "详细地址", "档案分", "考试分", "总分",
                "第一志愿", "第二志愿", "第三志愿", "第四志愿", "第五志愿", "第六志愿", "安置方式", "安置岗位");

        PlacementInfoDO alivePlacement = placementInfoService.getAlivePlacement(adminAreaCode);
        BizCheckUtil.checkNotNull(alivePlacement, "暂无安置");
        Boolean viewFlag = checkUniCanView(alivePlacement.getId());

        headers = FieldFilterUtils.filterHeader(headers, searchRequest.getFields());

        List<List<String>> data = Lists.newArrayList();
        if (!CollectionUtils.isEmpty(placementSoldierInfoDOList)) {
            for (PlacementSoldierInfoDO dto : placementSoldierInfoDOList) {
                List<String> item = Lists.newArrayList();
                if (headers.contains("姓名")) {
                    item.add(dto.getRealName());
                }

                if (headers.contains("身份证")) {
                    item.add(dto.getIdCardNo());
                }
                if (headers.contains("性别")) {
                    item.add(GenderEnum.getByEnumName(dto.getGender()).getDesc());
                }
                if (headers.contains("出生日期")) {
                    item.add(DateUtil.format(dto.getBirthday(), "yyyy-MM-dd"));
                }

                if (headers.contains("手机号")) {
                    item.add(dto.getMobile());
                }

                if (headers.contains("学历")) {
                    item.add(dto.getEducationLevel());
                }
                if (headers.contains("专业")) {
                    item.add(dto.getMajor());
                }
                if (headers.contains("详细地址")) {
                    item.add(dto.getResidentAddress());
                }

                if (headers.contains("档案分")) {
                    item.add(dto.getArchiveScore() != null ? String.valueOf(dto.getArchiveScore()) : "");
                }
                if (headers.contains("考试分")) {
                    item.add(dto.getExamScore() != null ? String.valueOf(dto.getExamScore()) : "");
                }
                if (headers.contains("总分")) {
                    item.add(dto.getTotalScore() != null ? String.valueOf(dto.getTotalScore()) : "");
                }


                if (headers.contains("第一志愿")) {
                    List<PlacementSoldierAspirationDO> aspirationDOS = placementSoldierAspirationService.listByIdCardNo(dto.getIdCardNo());

                    int aspSize = 0;
                    if (!CollectionUtils.isEmpty(aspirationDOS)) {
                        aspirationDOS = fillToSameBatch(aspirationDOS);
                        aspSize = aspirationDOS.size();
                    }
                    for (int i = 0; i < 6; i++) {
                        if (i < aspSize) {
                            PlacementPositionInfoDO cachedPlacementPosition = miniCacheUtils.getCachedPlacementPosition(aspirationDOS.get(i).getPositionId());
                            if (cachedPlacementPosition != null &&
                                    ((!PlacementBatchTypeEnum.UNIFIED.name().equals(cachedPlacementPosition.getType())) || (PlacementBatchTypeEnum.UNIFIED.name().equals(cachedPlacementPosition.getType())) && viewFlag)) {
                                item.add(cachedPlacementPosition.getUnitName() + "-" + cachedPlacementPosition.getName());
                            } else {
                                item.add("");
                            }
                        } else {
                            item.add("");
                        }
                    }
                }


                if (headers.contains("安置方式")) {
                    item.add(Strings.isNotBlank(dto.getPlacementType()) ? PlacementBatchTypeEnum.getByEnumName(dto.getPlacementType()).getDesc() : "");

                }

                if (headers.contains("安置岗位")) {
                    PlacementPositionInfoDO placementPosition = miniCacheUtils.getCachedPlacementPosition(dto.getPlacementPositionId());
                    if (placementPosition != null) {
                        item.add(placementPosition.getUnitName() + "-" + placementPosition.getName());
                    } else {
                        item.add("");
                    }
                }
                data.add(item);
            }
        }

        return ResponseUtils.buildSuccessResponse(new ExcelResultBO("安置", headers, data));
    }

    @Override
    public Boolean checkUniCanView(String placementId) {
        PlacementBatchDO placementBatchDO = placementBatchService.getByPlacementIdAndType(placementId, PlacementBatchTypeEnum.UNIFIED.name());
        String year = DateUtil.format(placementBatchDO.getCreateDatetime(), "yyyy");
        PlacementInfoDO placementInfoDO = placementInfoService.get(placementBatchDO.getPlacementId());
        String prefix = placementInfoDO.getAdminAreaCode() + year;

        CommonDataDictDO pw1 = commonDataDictService.getByCode(prefix + "pw1");
        if (pw1 != null && Boolean.TRUE.equals(pw1.getUsed())) {
            return true;
        }
        return false;
    }


    private List<PlacementSoldierAspirationDO> fillToSameBatch(List<PlacementSoldierAspirationDO> aspirationDOS) {
        aspirationDOS.sort(new Comparator<PlacementSoldierAspirationDO>() {
            @Override
            public int compare(PlacementSoldierAspirationDO o1, PlacementSoldierAspirationDO o2) {
                return o2.getCreateDatetime().compareTo(o1.getCreateDatetime());
            }
        });

        PlacementSoldierAspirationDO aspirationDO = aspirationDOS.get(0);
        String batchId = aspirationDO.getBatchId();

        List<PlacementSoldierAspirationDO> result = Lists.newArrayList(aspirationDO);
        for (int i = 1; i < aspirationDOS.size(); i++) {
            PlacementSoldierAspirationDO item = aspirationDOS.get(i);
            if (item.getBatchId().equals(batchId)) {
                result.add(item);
            }
        }


        result.sort(new Comparator<PlacementSoldierAspirationDO>() {
            @Override
            public int compare(PlacementSoldierAspirationDO o1, PlacementSoldierAspirationDO o2) {
                return o1.getSeqNo().compareTo(o2.getSeqNo());
            }
        });
        return result;
    }


    private Date dateStrToDate(String dateStr) {
        if (Strings.isBlank(dateStr)) {
            return null;
        }
        DateTime parse = DateUtil.parse(dateStr, "yyyy-MM-dd");
        Date date = parse.toJdkDate();
        return date;
    }


    private void checkSoldierImportTemplate(List<Object> headers, String... names) {
        for (int i = 0; i < names.length; i++) {
            BizCheckUtil.checkIsTrue(((String) headers.get(i)).startsWith(names[i]), "模板错误");
        }
    }


    @Override
    public BaseResponse<Integer> updatePlacementSoldierInfo(final PlacementSoldierInfoUpdateRequest updateRequest) {

        final BaseResponse<Integer> baseResponse = new BaseResponse<>();
        serviceTemplate.execute(transactionTemplate, baseResponse, new ServiceCallback() {
            @Override
            public void check() {
                BizCheckUtil.checkNotNull(updateRequest, "修改PlacementSoldierInfo的请求参数不能为空");
                BizCheckUtil.checkNotBlank(updateRequest.getId(), "id不能为空");
                BizCheckUtil.checkNotBlank(updateRequest.getModifierId(), "操作人不能为空");
                BizCheckUtil.checkNotBlank(updateRequest.getModifierType(), "操作人类型不能为空");
            }

            @Override
            public void executeService() {
                PlacementSoldierInfoDO placementSoldierInfoDO = PlacementSoldierInfoProviderConverter.convertRequestUO2DO(updateRequest);
                Integer affectRowNum = placementSoldierInfoService.update(placementSoldierInfoDO);
                ResponseUtils.setupSuccessResponse(baseResponse, affectRowNum);
            }

            @Override
            public ScenarioCodeEnum getScenarioEnum() {
                return ScenarioCodeEnum.PLACEMENT_SOLDIER_INFO_UPDATE;
            }
        });
        return baseResponse;
    }

    @Override
    public BaseResponse<Integer> changePw(PlacementSoldierInfoUpdateRequest updateRequest) {

        BizCheckUtil.checkNotNull(updateRequest, "请求参数不能为空");
        BizCheckUtil.checkNotBlank(updateRequest.getSoldierId(), "请求参数不能为空");
        BizCheckUtil.checkNotBlank(updateRequest.getIdCardNo(), "请求参数不能为空");
        BizCheckUtil.checkNotBlank(updateRequest.getNewPassword(), "请求参数不能为空");

        PlacementSoldierInfoDO bySoldierId = placementSoldierInfoService.getBySoldierId(updateRequest.getSoldierId());
        BizCheckUtil.checkIsTrue(bySoldierId != null, "身份证错误");
        BizCheckUtil.checkIsTrue(bySoldierId.getIdCardNo().equals(updateRequest.getIdCardNo()), "无法修改其他人的密码");
        String encode = PasswordUtils.encode(updateRequest.getIdCardNo(), updateRequest.getNewPassword());
        bySoldierId.setPassword(encode);
        Integer update = placementSoldierInfoService.update(bySoldierId);

        return ResponseUtils.buildSuccessResponse(update);
    }

    @Override
    public BaseResponse<Integer> updateSoldierInfo(PlacementSoldierInfoUpdateRequest request) {

        BizCheckUtil.checkNotNull(request, "请求不能为空");
        BizCheckUtil.checkNotNull(request.getIdCardNo(), "请求不能为空");

        PlacementSoldierInfoDO basicInfo = placementSoldierInfoService.getByIdCardNo(request.getIdCardNo());
        BizCheckUtil.checkNotNull(basicInfo, "查无此人");

        if (Strings.isNotBlank(request.getResidentAddress())) {
            basicInfo.setResidentAddress(request.getResidentAddress());
        }
        if (Strings.isNotBlank(request.getMobile())) {
            basicInfo.setMobile(request.getMobile());
        }
        if (Strings.isNotBlank(request.getAvatarPath())) {
            basicInfo.setAvatarPath(request.getAvatarPath());
        }
        if (Strings.isNotBlank(request.getRealName())) {
            basicInfo.setRealName(request.getRealName());
        }
        if (Strings.isNotBlank(request.getGender())) {
            basicInfo.setGender(request.getGender());
        }
        if (Strings.isNotBlank(request.getEducationLevel())) {
            basicInfo.setEducationLevel(request.getEducationLevel());
        }
        if (Strings.isNotBlank(request.getHouseholdRegisterType())) {
            basicInfo.setHouseholdRegisterType(request.getHouseholdRegisterType());
        }
        if (Strings.isNotBlank(request.getPoliticalOutlook())) {
            basicInfo.setPoliticalOutlook(request.getPoliticalOutlook());
        }
        if (Strings.isNotBlank(request.getSoldierType())) {
            basicInfo.setSoldierType(request.getSoldierType());
        }
        if (Strings.isNotBlank(request.getLabels())) {
            basicInfo.setLabels(request.getLabels());
        }
        if (request.getBirthday() != null) {
            basicInfo.setBirthday(request.getBirthday());
        }
        if (request.getArchiveScore() != null) {
            basicInfo.setArchiveScore(request.getArchiveScore());
        }
        if (Strings.isNotBlank(request.getMaritalStatus())) {
            basicInfo.setMaritalStatus(request.getMaritalStatus());
        }
        if (Strings.isNotBlank(request.getEmergencyName())) {
            basicInfo.setEmergencyName(request.getEmergencyName());
        }
        if (Strings.isNotBlank(request.getEmergencyRelationship())) {
            basicInfo.setEmergencyRelationship(request.getEmergencyRelationship());
        }
        if (Strings.isNotBlank(request.getEmergencyMobile())) {
            basicInfo.setEmergencyMobile(request.getEmergencyMobile());
        }
        if (Strings.isNotBlank(request.getCollege())) {
            basicInfo.setCollege(request.getCollege());
        }
        if (Strings.isNotBlank(request.getMajor())) {
            basicInfo.setMajor(request.getMajor());
        }
        if (Strings.isNotBlank(request.getJobLevel())) {
            basicInfo.setJobLevel(request.getJobLevel());
        }
        if (Strings.isNotBlank(request.getCivilianLevel())) {
            basicInfo.setCivilianLevel(request.getCivilianLevel());
        }
        if (Strings.isNotBlank(request.getYjfs())) {
            basicInfo.setYjfs(request.getYjfs());
        }
        if (request.getArchiveScore() != null) {
            basicInfo.setArchiveScore(request.getArchiveScore());
        }
        if (request.getEntryDatetime() != null) {
            basicInfo.setEntryDatetime(request.getEntryDatetime());
        }
        if (request.getArchiveScoreInfo() != null) {
            basicInfo.setArchiveScoreDetail(JSON.toJSONString(request.getArchiveScoreInfo()));
            Double total = request.getArchiveScoreInfo().getDouble("total");
            basicInfo.setArchiveScore(total);
        }

        basicInfo.setModifierId(request.getModifierId());
        basicInfo.setModifierType(request.getModifierType());
        Integer update = placementSoldierInfoService.update(basicInfo);
        return ResponseUtils.buildSuccessResponse(update);
    }

    @Override
    public BaseResponse<Integer> updateSoldierInfoBySoldier(PlacementSoldierInfoUpdateRequest request) {

        BizCheckUtil.checkNotNull(request, "请求不能为空");
        BizCheckUtil.checkNotNull(request.getSoldierId(), "请求不能为空");

        PlacementSoldierInfoDO basicInfo = placementSoldierInfoService.getBySoldierId(request.getSoldierId());
        BizCheckUtil.checkNotNull(basicInfo, "查无此人");

        if (Strings.isNotBlank(request.getMobile())) {
            basicInfo.setMobile(request.getMobile());
        }
        if (Strings.isNotBlank(request.getAvatarPath())) {
            basicInfo.setAvatarPath(request.getAvatarPath());
        }
        if (Strings.isNotBlank(request.getGender())) {
            basicInfo.setGender(request.getGender());
        }
        if (request.getBirthday() != null) {
            basicInfo.setBirthday(request.getBirthday());
        }
        if (Strings.isNotBlank(request.getCollege())) {
            basicInfo.setCollege(request.getCollege());
        }
        if (Strings.isNotBlank(request.getMajor())) {
            basicInfo.setMajor(request.getMajor());
        }
        if (Strings.isNotBlank(request.getMaritalStatus())) {
            basicInfo.setMaritalStatus(request.getMaritalStatus());
        }
        if (Strings.isNotBlank(request.getEmergencyName())) {
            basicInfo.setEmergencyName(request.getEmergencyName());
        }
        if (Strings.isNotBlank(request.getEmergencyRelationship())) {
            basicInfo.setEmergencyRelationship(request.getEmergencyRelationship());
        }
        if (Strings.isNotBlank(request.getEmergencyMobile())) {
            basicInfo.setEmergencyMobile(request.getEmergencyMobile());
        }
        basicInfo.setModifierId(request.getModifierId());
        basicInfo.setModifierType(request.getModifierType());
        Integer update = placementSoldierInfoService.update(basicInfo);
        return ResponseUtils.buildSuccessResponse(update);
    }

    @Transactional
    @Override
    public BaseResponse<Integer> representArchiveScore(CommonRepresentationRecordInsertRequest request) {

        BizCheckUtil.checkNotNull(request, "请求参数不能为空");
        BizCheckUtil.checkNotBlank(request.getSoldierId(), "id不能为空");

        final CommonRepresentationRecordDO recordDO = CommonRepresentationRecordProviderConverter.convertRequestIO2DO(request);
        if (request.getId() == null) {
            PlacementSoldierInfoDO bySoldierId = placementSoldierInfoService.getBySoldierId(request.getSoldierId());
            BizCheckUtil.checkNotNull(bySoldierId, "查无此人");


            recordDO.setBizId(bySoldierId.getId());
            recordDO.setBizType(PlacementRepresentationTypeEnum.SCORE.name());
            recordDO.setType(RepresentationTypeEnum.PLACEMENT.name());
            recordDO.setStatus(ProcessStatusEnum.DEALING.name());
            recordDO.setIdCardNo(bySoldierId.getIdCardNo());
            recordDO.setRealName(bySoldierId.getRealName());
            commonRepresentationRecordService.insert(recordDO);

            placementEventRecordService.insertEventRecord(bySoldierId.getSoldierId(), bySoldierId.getIdCardNo(), bySoldierId.getRealName(), "提交了申诉！");
        } else {
            CommonRepresentationRecordDO oldOne = commonRepresentationRecordService.get(request.getId());
            BizCheckUtil.checkNotNull(oldOne, "不存在");
            recordDO.setId(oldOne.getId());
            recordDO.setStatus(ProcessStatusEnum.DEALING.name());
            commonRepresentationRecordService.update(recordDO);
        }

        return ResponseUtils.buildSuccessResponse(0);
    }

    @Override
    public BaseResponse<Integer> representBasicInfo(CommonRepresentationRecordInsertRequest request) {

        BizCheckUtil.checkNotNull(request, "请求参数不能为空");
        BizCheckUtil.checkNotBlank(request.getSoldierId(), "id不能为空");

        PlacementSoldierInfoDO bySoldierId = placementSoldierInfoService.getBySoldierId(request.getSoldierId());
        BizCheckUtil.checkNotNull(bySoldierId, "查无此人");


        final CommonRepresentationRecordDO recordDO = CommonRepresentationRecordProviderConverter.convertRequestIO2DO(request);
        recordDO.setBizId(bySoldierId.getId());
        recordDO.setBizType(PlacementRepresentationTypeEnum.BASIC_INFO.name());
        recordDO.setType(RepresentationTypeEnum.PLACEMENT.name());
        recordDO.setStatus(ProcessStatusEnum.DEALING.name());
        recordDO.setIdCardNo(bySoldierId.getIdCardNo());
        recordDO.setRealName(bySoldierId.getRealName());
        Integer insert = commonRepresentationRecordService.insert(recordDO);

        PlacementEventRecordDO event = new PlacementEventRecordDO();
        event.setSoldierId(bySoldierId.getSoldierId());
        event.setIdCardNo(bySoldierId.getIdCardNo());
        event.setRealName(bySoldierId.getRealName());
        event.setDetail("提交了信息申诉");
        placementEventRecordService.insert(event);
        return ResponseUtils.buildSuccessResponse(insert);
    }

    @Override
    public BaseResponse<CommonRepresentationRecordDTO> getMyRepresent(String soldierId) {

        BizCheckUtil.checkNotNull(soldierId, "请求参数不能为空");
        PlacementSoldierInfoDO bySoldierId = placementSoldierInfoService.getBySoldierId(soldierId);
        BizCheckUtil.checkNotNull(bySoldierId, "查无此人");

        List<CommonRepresentationRecordDO> commonRepresentationRecordDOS = commonRepresentationRecordService.listByIdCardNoAndType(bySoldierId.getIdCardNo(),
                RepresentationTypeEnum.PLACEMENT.name());
        if (CollectionUtils.isEmpty(commonRepresentationRecordDOS)) {
            return ResponseUtils.buildSuccessResponse(null);
        }
        final CommonRepresentationRecordDTO remoteObj = CommonRepresentationRecordProviderConverter.convertResponseDO2DTO(commonRepresentationRecordDOS.get(0));
        return ResponseUtils.buildSuccessResponse(remoteObj);
    }

    @Override
    public BasePagingResponse<List<CommonRepresentationRecordDTO>> listMyRepresent(CommonRepresentationRecordSearchRequest request) {

        BizCheckUtil.checkNotNull(request, "请求参数不能为空");
        BizCheckUtil.checkNotNull(request.getSoldierId(), "soldierId不能为空");
        PlacementSoldierInfoDO bySoldierId = placementSoldierInfoService.getBySoldierId(request.getSoldierId());
        BizCheckUtil.checkNotNull(bySoldierId, "查无此人");

        final CommonRepresentationRecordBSearcher commonRepresentationRecordBSearcher = CommonRepresentationRecordProviderConverter.convertRequestSO2Searcher(request);
        commonRepresentationRecordBSearcher.setType(RepresentationTypeEnum.PLACEMENT.name());
        final List<CommonRepresentationRecordDO> commonRepresentationRecordDOList = commonRepresentationRecordService.search(commonRepresentationRecordBSearcher);
        final List<CommonRepresentationRecordDTO> commonRepresentationRecordDTOList = CommonRepresentationRecordProviderConverter.convertResponseDOList2DTOList(commonRepresentationRecordDOList);

        return ResponseUtils.buildSuccessPagingResponse(commonRepresentationRecordDTOList, commonRepresentationRecordBSearcher);
    }

    @Transactional
    @Override
    public BaseResponse<Integer> confirmArchiveScore(PlacementSoldierInfoUpdateRequest request) {


        BizCheckUtil.checkNotNull(request, "请求参数不能为空");
        BizCheckUtil.checkNotBlank(request.getSoldierId(), "id不能为空");
        BizCheckUtil.checkNotBlank(request.getScoreSign(), "签名不能为空");
        BizCheckUtil.checkNotBlank(request.getScoreFaceRecognitionId(), "人脸不能为空");

        PlacementSoldierInfoDO bySoldierId = placementSoldierInfoService.getBySoldierId(request.getSoldierId());
        bySoldierId.setScoreReviewStatus(PlacementScoreReviewEnum.PASS.name());
        bySoldierId.setScoreReviewDatetime(new Date());
        bySoldierId.setScoreSign(request.getScoreSign());
        bySoldierId.setScoreFaceRecognitionId(request.getScoreFaceRecognitionId());
        Integer update = placementSoldierInfoService.update(bySoldierId);

        placementEventRecordService.insertEventRecord(bySoldierId.getSoldierId(), bySoldierId.getIdCardNo(), bySoldierId.getRealName(), "完成档案分的审核！");
        return ResponseUtils.buildSuccessResponse(update);
    }

    @Override
    public BaseResponse<Integer> confirmBaseInfo(PlacementSoldierInfoUpdateRequest request) {


        BizCheckUtil.checkNotNull(request, "请求参数不能为空");
        BizCheckUtil.checkNotBlank(request.getSoldierId(), "id不能为空");
        BizCheckUtil.checkNotBlank(request.getBaseSign(), "签名不能为空");


        PlacementSoldierInfoDO bySoldierId = placementSoldierInfoService.getBySoldierId(request.getSoldierId());
        bySoldierId.setBaseReviewStatus(PlacementScoreReviewEnum.PASS.name());
        bySoldierId.setBaseReviewDatetime(new Date());
        bySoldierId.setBaseSign(request.getBaseSign());
        bySoldierId.setBaseFaceRecognitionId(request.getBaseFaceRecognitionId());
        Integer update = placementSoldierInfoService.update(bySoldierId);

        placementEventRecordService.insertEventRecord(bySoldierId.getSoldierId(), bySoldierId.getIdCardNo(), bySoldierId.getRealName(), "完成个人信息的审核！");
        return ResponseUtils.buildSuccessResponse(update);
    }

    @Override
    public BaseResponse<Integer> publishAllSoldier(PlacementSoldierInfoUpdateRequest request) {


        BizCheckUtil.checkNotNull(request, "请求参数不能为空");
        BizCheckUtil.checkNotNull(request.getIdList(), "请求参数不能为空");
        String adminAreaCode = govOrgService.getAdminAreaCodeOfEmploy(request.getEmployeeId());
        PlacementInfoDO alivePlacement = placementInfoService.getAlivePlacement(adminAreaCode);
        BizCheckUtil.checkNotNull(alivePlacement, "暂无安置");

        for (String id : request.getIdList()) {
            PlacementSoldierInfoDO soldierInfoDO = placementSoldierInfoService.get(id);
            soldierInfoDO.setPublished(true);
            RequestSetUtils.setModifierInfo(soldierInfoDO, request);
            placementSoldierInfoService.update(soldierInfoDO);
        }

        return ResponseUtils.buildSuccessResponse(0);
    }


    @Transactional
    @Override
    public BaseResponse<Integer> geneOfflineBatch(PlacementSoldierInfoUpdateRequest request) {


        BizCheckUtil.checkNotNull(request, "请求参数不能为空");
        BizCheckUtil.checkNotNull(request.getPublishDatetime(), "publishDatetime不能为空");

        String adminAreaCode = govOrgService.getAdminAreaCodeOfEmploy(request.getEmployeeId());
        PlacementInfoDO alivePlacement = placementInfoService.getAlivePlacement(adminAreaCode);
        BizCheckUtil.checkNotNull(alivePlacement, "暂无安置");

        PlacementBatchDO batchInfo = placementBatchService.getByPlacementIdAndType(alivePlacement.getId(), PlacementBatchTypeEnum.OFFLINE.name());
        if (batchInfo == null) {
            batchInfo = insertOfflineBatch(alivePlacement, request);
        }


        return ResponseUtils.buildSuccessResponse(0);
    }

    private PlacementBatchDO insertOfflineBatch(PlacementInfoDO alivePlacement, PlacementSoldierInfoUpdateRequest request) {
        PlacementBatchDO batchDO = new PlacementBatchDO();
        batchDO.setPlacementId(alivePlacement.getId());
        batchDO.setSeqNo(2);
        batchDO.setStartDatetime(request.getApplyStartDatetime() != null ? request.getApplyStartDatetime() : new Date());
        batchDO.setApplyEndDatetime(request.getApplyStartDatetime() != null ? request.getApplyStartDatetime() : new Date());
        batchDO.setApplyEndDatetime(request.getPublishDatetime());
        batchDO.setPublishDatetime(request.getPublishDatetime());
        batchDO.setStatus(ProcessStatusEnum.DEALING.name());
        batchDO.setType(PlacementBatchTypeEnum.OFFLINE.name());
        batchDO.setPublished(true);
        batchDO.setCanApply(true);
        placementBatchService.insert(batchDO);
        return batchDO;
    }


    @Override
    public BaseResponse<Integer> deletePlacementSoldierInfo(final BaseDeleteRequest deleteRequest) {

        final BaseResponse<Integer> baseResponse = new BaseResponse<>();
        serviceTemplate.execute(transactionTemplate, baseResponse, new ServiceCallback() {
            @Override
            public void check() {
                BizCheckUtil.checkNotNull(deleteRequest, "逻辑删除PlacementSoldierInfo的请求参数不能为空");
                BizCheckUtil.checkNotBlank((String) deleteRequest.getId(), "id不能为空");
                BizCheckUtil.checkNotBlank(deleteRequest.getModifierType(), "操作人类型不能为空");
                BizCheckUtil.checkNotBlank((String) deleteRequest.getModifierId(), "操作人不能为空");
            }

            @Override
            public void executeService() {
                final Integer affectRowNum = placementSoldierInfoService.delete((String) deleteRequest.getId(), deleteRequest.getModifierType(), (String) deleteRequest.getModifierId());
                ResponseUtils.setupSuccessResponse(baseResponse, affectRowNum);
            }

            @Override
            public ScenarioCodeEnum getScenarioEnum() {
                return ScenarioCodeEnum.PLACEMENT_SOLDIER_INFO_DELETE_LOGICALLY;
            }
        });
        return baseResponse;
    }


    @Override
    public BaseResponse<PlacementBatchDTO> viewDeadline(PlacementInfoSearchRequest request) {

        BizCheckUtil.checkNotNull(request.getSoldierId(), "soldierId不能为空");
        PlacementSoldierInfoDO bySoldierId = placementSoldierInfoService.getBySoldierId(request.getSoldierId());
        BizCheckUtil.checkNotNull(bySoldierId, "查无此人");
        if (Strings.isNotBlank(bySoldierId.getPlacementPositionId())) {
            return ResponseUtils.buildSuccessResponse(new PlacementBatchDTO());
        }

        PlacementBatchDO currentBatch = placementBatchService.getCurrentBatch(bySoldierId.getPlacementId());
        if (currentBatch == null) {
            return ResponseUtils.buildSuccessResponse(new PlacementBatchDTO());
        }

        PlacementBatchDTO placementBatchDTO = PlacementBatchProviderConverter.convertResponseDO2DTO(currentBatch);
        if (PlacementBatchTypeEnum.UNIFIED.name().equals(currentBatch.getType())) {
            String format = String.format("请在%s前完成志愿填报，逾期未填报的由杭州市退役军人事务局进行指定性安置！", DateUtil.format(currentBatch.getApplyEndDatetime(), "yyyy-MM-dd"));
            placementBatchDTO.setTip(format);
        }

        return ResponseUtils.buildSuccessResponse(placementBatchDTO);
    }

}
